package com.laivi.basic.model.datastruct;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.laivi.basic.util.DataUtil;

/**
 * @author laivi.zhu@gmail.com
 * @date 2013-12-11
 * description:权重对象，对象统计操作类
 */
@SuppressWarnings("serial")
public class WeightMap<T> extends LinkedHashMap<T,Integer>{
	//********************************构造权重随机数的参数和方法**************************
	private List<T> objs;
	private boolean isWeight=false;						//说明对象是否是用于权重操作
	public static<T> WeightMap<T> createMap(boolean isWeight){
		WeightMap<T> weight=new WeightMap<T>();
		if(isWeight){
			weight.objs=new ArrayList<T>();
			weight.isWeight=isWeight;
		}
		return weight;
	}
	
	public WeightMap<T> add(T id,Integer value){
		if(this.isWeight){
			objs.add(id);
		}
		this.put(id, value);
		return this;
	}
	
	public T getIndexObjs(int index){
		if(this.isWeight){
			return objs.get(index);
		}else{
			return null;
		}
	}
	//********************************构造统计的方法**************************
	public WeightMap<T> add(T obj){
		if(this.get(obj)!=null){
			this.put(obj, this.get(obj)+1);
		}else{
			this.put(obj,1);
		}
		return this;
	}
	
	public Map<T,Integer> sort(final boolean isKey){
		Map<T,Integer> map=new LinkedHashMap<T,Integer>();
		List<Map.Entry<T, Integer>> mapList=new ArrayList<Map.Entry<T,Integer>>(map.entrySet());
		Collections.sort(mapList, new Comparator<Map.Entry<T,Integer>>(){
			@Override
			public int compare(java.util.Map.Entry<T, Integer> o1,
					java.util.Map.Entry<T, Integer> o2) {
				if(isKey){
					return o2.getKey().toString().compareTo(o1.getKey().toString());
				}else{
					return o2.getValue()-o1.getValue();
				}
			}});
		for(Map.Entry<T, Integer> entry:mapList){
			map.put(entry.getKey(), entry.getValue());
		}
		return map;
	}
	
	public void printResult(boolean isRate){
		double total=0;
		if(isRate){
			for(Map.Entry<T, Integer>entry:this.entrySet()){
				total+=entry.getValue();
			}
		}
		for(Map.Entry<T, Integer>entry:this.entrySet()){
			System.out.print(entry.getKey()+"对象有"+entry.getValue()+"个。");
			if(isRate){
				System.out.println("占全部的:"+DataUtil.getPercent(entry.getValue()/total, 2));
			}else{
				System.out.println();
			}
		}
	}
	
}
